package com.thewell79.areadiary;

import android.app.Application;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.thewell79.areadiary.data.UserData;

/**
 * Created by THEWELL-LOBBY on 2015-04-22.
 */
public class BaseApplication extends Application {

    private static BaseApplication mInstance;
    private RequestQueue mQueue;
    private ImageLoader mImageLoader;
    private UserData user;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized BaseApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getQueue() {
        if (mQueue == null) {
            mQueue = Volley.newRequestQueue(this);
        }
        return mQueue;
    }

    public ImageLoader getImageloader() {
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(getQueue(), new BitmapLruCache() );
        }

        return mImageLoader;
    }

    public void addQueue(Request request) {
        getQueue().add(request);
    }

    public UserData getUser() {
        return user;
    }

    public void setUser(UserData user) {
        this.user = user;
    }

    private static class BitmapLruCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {

        public BitmapLruCache() {
            super(getDefaultLruCacheSize());
        }

        private static int getDefaultLruCacheSize() {
            int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
            int cacheSize = maxMemory / 8;

            return  cacheSize;
        }

        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight() / 1024;
        }

        @Override
        public Bitmap getBitmap(String url) {
            return get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            put(url, bitmap);
        }
    }
}